<template>
  <div class="server-monitor">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="box-card" v-loading="loading">
          <div slot="header" class="clearfix">
            <span>服务器信息</span>
          </div>
          <el-table :data="serverInfo" border stripe>
            <el-table-column prop="name" label="参数" width="200"></el-table-column>
            <el-table-column prop="value" label="值"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="box-card" v-loading="loading">
          <div slot="header" class="clearfix">
            <span>CPU使用率</span>
          </div>
          <div style="padding: 20px">
            <el-progress type="dashboard" :percentage="cpuUsage" :color="customColors"></el-progress>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="box-card" v-loading="loading">
          <div slot="header" class="clearfix">
            <span>内存使用率</span>
          </div>
          <div style="padding: 20px">
            <el-progress type="dashboard" :percentage="memoryUsage" :color="customColors"></el-progress>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card" v-loading="loading">
          <div slot="header" class="clearfix">
            <span>服务器实时监控</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="fetchData" :disabled="loading">
              <i class="el-icon-refresh" :class="{'is-loading': loading}"></i> 刷新
            </el-button>
          </div>
          <el-table :data="monitorData" border stripe>
            <el-table-column prop="name" label="监控项" width="200"></el-table-column>
            <el-table-column prop="value" label="当前值"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'Server',
  data() {
    return {
      loading: false,
      // CPU和内存使用率
      cpuUsage: 0,
      memoryUsage: 0,
      
      // 自定义进度条颜色
      customColors: [
        {color: '#67C23A', percentage: 60},
        {color: '#E6A23C', percentage: 80},
        {color: '#F56C6C', percentage: 100}
      ],

      // 服务器基本信息
      serverInfo: [],
      
      // 实时监控数据
      monitorData: [],

      // 定时器
      timer: null
    }
  },
  methods: {
    async fetchData() {
      if (this.loading) return
      
      this.loading = true
      try {
        // 获取系统信息
        const [serviceRes, systemRes] = await Promise.all([
          this.$api.monitor.getServiceInfo(),
          this.$api.monitor.getSystemInfo()
        ])

        if (serviceRes.code === 200 && systemRes.code === 200) {
          const serviceData = serviceRes.data
          const systemData = systemRes.data
          
          // 更新服务器信息
          this.serverInfo = [
            {name: '服务器名称', value: serviceData.serverHostname || 'localhost'},
            {name: '操作系统', value: `${serviceData.osName || 'Windows'} ${serviceData.osVersion || '10'}`},
            {name: 'Java版本', value: serviceData.javaVersion || 'JDK 1.8'},
            {name: '服务器IP', value: serviceData.serverIp || '127.0.0.1'},
            {name: '系统架构', value: serviceData.osArch || 'x86_64'}
          ]
          
          // 更新CPU和内存使用率
          const cpuLoad = serviceData.systemCpuLoad ? parseFloat(serviceData.systemCpuLoad) : 0
          this.cpuUsage = Math.round(cpuLoad)
          
          const totalMemory = parseInt(serviceData.totalMemory || '0')
          const freeMemory = parseInt(serviceData.freeMemory || '0')
          const usedMemory = totalMemory - freeMemory
          this.memoryUsage = totalMemory > 0 ? Math.round((usedMemory / totalMemory) * 100) : 0
          
          // 获取运行时间（从秒转换为小时）
          const runningTimeStr = serviceData.runningTime || '0秒'
          const runningSeconds = parseInt(runningTimeStr.replace('秒', ''))
          const uptimeHours = (runningSeconds / 3600).toFixed(1)
          
          // 更新监控数据
          this.monitorData = [
            {name: '在线用户数', value: serviceData.onlineUsers || 0, unit: '人'},
            {name: '系统运行时间', value: uptimeHours, unit: '小时'},
            {name: '系统启动时间', value: serviceData.startTime || '-', unit: ''},
            {name: 'CPU核心数', value: systemData.availableProcessors || '-', unit: '核'},
            {name: '系统CPU使用率', value: serviceData.systemCpuLoad || '-', unit: ''},
            {name: '当前应用CPU使用率', value: serviceData.processCpuLoad || '-', unit: ''},
            {name: '可用内存', value: serviceData.freeMemory || '-', unit: ''},
            {name: '总内存', value: serviceData.totalMemory || '-', unit: ''}
          ]
          
          this.$message({
            type: 'success',
            message: '数据已刷新'
          })
        } else {
          throw new Error(serviceRes.msg || systemRes.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取服务器信息失败:', error)
        this.$message.error(error.message || '获取服务器信息失败')
      } finally {
        this.loading = false
      }
    },
    startTimer() {
      this.stopTimer()
      this.timer = setInterval(() => {
        this.fetchData()
      }, 30000)
    },
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  },
  mounted() {
    this.fetchData()
    this.startTimer()
  },
  beforeDestroy() {
    this.stopTimer()
  }
}
</script>

<style lang="scss" scoped>
.server-monitor {
  padding: 20px;
  
  .box-card {
    margin-bottom: 20px;
    
    .el-progress {
      margin: 0 auto;
      display: block;
    }
  }
  
  .el-table {
    margin-top: 10px;
  }

  .is-loading {
    animation: rotating 2s linear infinite;
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 